/**
 * Created by leiweibo on 6/28/15.
 */

'use strict'
var app = angular.module('vistrackcontroller', []);

app.filter('offset', function () {
  return function (input, start) {
    start = parseInt(start, 10);
    return input.slice(start);
  };
});

var countMap = {};
var getuploader = function(url, brwoswerBtnStr, container, percentage) {
  var options = {
    'expiration': Math.floor(new Date().getTime() / 1000) + 86400,
    bucket: 'vistrack-attach-prd',
    'save-key': '/{filemd5}{.suffix}'
  };
  // 查看更多参数：http://docs.upyun.com/api/form_api/#表单API接口简介
  var policy = window.btoa(JSON.stringify(options));
  // 从 UPYUN 用户管理后台获取表单 API
  //  var form_api_secret = 'uWXYXiFzo9SwavwderRAIyYJCjg=';
  var form_api_secret = '5ri+TpAfi0lw+O9eaH9PBMYoSHI=';
  // 计算签名
  var signature = md5(policy + '&' + form_api_secret);
  var url_prefix = "http://" + options.bucket + ".b0.upaiyun.com";
  var uploader = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: brwoswerBtnStr, // you can pass in id...
    container: document.getElementById(container),
    flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
    multi_selection:false,
    url: 'http://v0.api.upyun.com/' + options.bucket,

    multipart_params: {
      'Filename': '${filename}', // adding this to keep consistency across the runtimes
      'Content-Type': '',
      'policy': policy,
      'signature': signature
    },

    init: {
      PostInit: function () {
        //do nothing here.
      },

      FilesAdded: function (up, files) {
        plupload.each(files, function (file) {
          uploader.start();
        });
      },

      UploadProgress: function (up, file) {
        if ($("#" + percentage) && $("#" + percentage).size() > 0) {
          $("#" + percentage).text(file.percent + "%");
        } else {
          $('#percentage').text(file.percent + "%");
        }

      },

      FileUploaded: function (up, file, info) {
        var response = JSON.parse(info.response);
        //array.push(url_prefix + response.url);
        url = url_prefix + response.url;
      },

      Error: function (up, err) {
        $("#" + percentage).text("上传失败");
      }
    }
  });
  uploader.init();
}


app.controller('VistrackCtrl', function($scope, $window, $filter, $compile, PatientService, VistrackService, DiseaseService, ProvinceService, HospitalService, OfficeService, DoctorService) {
  $scope.after_examines_url = {};
  $scope.after_checks_url = {};
  $scope.after_evaluations_url = {};

  $scope.$watch('vistrack_time', function (newValue) {
    $scope.vistrack_time = $filter('date')(newValue, 'yyyy/MM/dd');
  });

  getuploader($scope.after_checks_url, 'browser_vistrack_check', 'container_vistrack_check', 'percentage_check');
  getuploader($scope.after_examines_url, 'browser_vistrack_examine', 'container_vistrack_examine', 'percentage_examine');
  getuploader($scope.after_evaluations_url, 'browser_vistrack_evaluation', 'container_vistrack_evaluation', 'percentage_evaluation');


  $scope.provinces = ProvinceService.list(function(data) {
    $scope.provinces = data.provinces
  });

  $scope.diseases = DiseaseService.list(function(data) {
    $scope.diseases = data.diseases;
  });

  $scope.provinceChanged = function(provinceId) {
    $scope.hospitals = HospitalService.list_by_province(provinceId, function(res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }
      $scope.hospitals = res.hospitals;
    });
  }

  $scope.hospitalChanged = function (hospitalId) {
    OfficeService.list_by_hospital(hospitalId, function (res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }

      $scope.offices = res.offices;
    });
  };

  $scope.officeChanged = function(officeId) {
    DoctorService.list_by_office(officeId, function(res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }

      $scope.doctors = res.doctors;
    });
  };

  $scope.doctorChanged = function() {
    if (!$scope.doctor) {
      alert('请选择医生之后重新选择疾病分类');
    } else {
      // province, hospital, office, doctor, disease, success) {
      PatientService.list($scope.office, $scope.doctor, function(res) {
        if (res.result == false) {
          $scope.error_msg = res.message;
        }

        $scope.patients = res.patients;
      });
    }
  }

  $scope.submit = function() {

    var examineAttachment = new Attachment($scope.after_examine_desc, $scope.after_examines_url.url);
    var checkAttachment = new Attachment($scope.after_check_desc, $scope.after_checks_url.url);
    var evaluationAttachment = new Attachment($scope.after_evaluation_desc, $scope.after_evaluations_url);

    var formData = {
      province: $scope.province,
      hospital: $scope.hospital,
      office:$scope.office,
      doctor: $scope.doctor,
      vistrack_time: $scope.vistrack_time,
      disease: $scope.disease,
      patient: $scope.patient,
      after_examin: examineAttachment,
      after_check: checkAttachment,
      after_evaluation: evaluationAttachment,
      evaluation: $scope.evaluation
    };

    VistrackService.create(formData, function(res) {
      if (res.result == true) {
        delete $scope.province;
        delete $scope.hospital;
        delete $scope.office;
        delete $scope.doctor;
        delete $scope.vistrack_time;
        delete $scope.patient;
        delete $scope.after_examin;
        delete $scope.after_check;
        delete $scope.after_evaluation;
        delete $scope.evaluation;

        delete $scope.after_examine_desc;
        delete $scope.after_check_desc;
        delete $scope.after_evaluation_desc;

        $('div[id^=percentage_]').text('');
        alert('添加随访信息成功！');
      } else {
        $scope.error_msg = res.message;
      }
    }, function(data, status) {
      $scope.error_msg = '无权限进行此操作';
    });
  }

  $scope.role = $window.sessionStorage.role;
  if ($scope.role == 4 && $window.sessionStorage.hospital) {
    $scope.hospitalChanged($window.sessionStorage.hospital);
  }
});


var Attachment = function(desc, url) {
  this.url = url;
  this.desc = desc;
}
var transformToArray = function(descArr) {
  var arr = Object.keys(descArr).map(function (key) {return descArr[key]});
  return arr;
}